package com.sailfish.springbootdemo.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.sailfish.springbootdemo.common.DB1EmailTemplates;
import com.sailfish.springbootdemo.dao.db1.*;
import com.sailfish.springbootdemo.dao.db4.UserDao;
import com.sailfish.springbootdemo.dao.db6.CompanyInfoDao;
import com.sailfish.springbootdemo.pojo.Result;
import com.sailfish.springbootdemo.pojo.db1.*;
import com.sailfish.springbootdemo.pojo.db2.MailAddress;
import com.sailfish.springbootdemo.pojo.db4.User;
import com.sailfish.springbootdemo.pojo.db6.CompanyInfo;
import com.sailfish.springbootdemo.service.db1.CoreAlgorithmService;
import com.sailfish.springbootdemo.service.db1.ThirdApiSendService;
import com.sailfish.springbootdemo.service.db2.ThirdApiService;
import com.sailfish.springbootdemo.utils.redis.RedisCRUD;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.config.IntervalTask;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

@Component
public class ScheduleTasks {

    @Autowired
    private CoreAlgorithmService coreAlgorithmService;

    @Autowired
    private ThirdApiSendService thirdApiSendService;

    @Autowired
    private PcbaLineDao pcbaLineDao;

    @Autowired
    private PcbaDeviceDao pcbaDeviceDao;

    @Autowired
    private PcbaDeviceTypeDao pcbaDeviceTypeDao;

    @Autowired
    private PcbaCompanyDao pcbaCompanyDao;

    @Autowired
    private PcbaWorkshopDao pcbaWorkshopDao;

    @Autowired
    private LineLevelDao lineLevelDao;

    @Autowired
    private ThirdApiService thirdApiService;

    @Autowired
    private PcbaDeviceResourceDao pcbaDeviceResourceDao;

    @Autowired
    private TaskScheduler taskScheduler;

    @Autowired
    private MaintenanceConfigDao maintenanceConfigDao;

    @Autowired
    private BrandDao brandDao;

    @Autowired
    private BrandTypeDao brandTypeDao;

    @Autowired
    private UserDao userDao;

    private ScheduledFuture<?> scheduledFuture;

    @Autowired
    private RedisCRUD redisCRUD;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CompanyInfoDao companyInfoDao;

    @Value("${personal.config.sso.trusted-redirect-uri}")
    private String trustedRedirectUri;

    /**
     * 刷新设备保养计划定时器
     */
    //@Scheduled(fixedRate = 1000 * 3600 * 24) // 每 24小时 执行一次 （单位ms）
    @Scheduled(cron = "0 0 1 * * ?") // 每天凌晨1点执行
    public void refreshDeviceUpkeepStatusTask() {
        System.out.println("[refreshDeviceUpkeepStatusTask] 定时任务开始执行: " + CommonUtils.formatCurrentTime());

        coreAlgorithmService.refreshDeviceUpkeepStatus(null);

        System.out.println("[refreshDeviceUpkeepStatusTask] 定时任务结束执行: " + CommonUtils.formatCurrentTime());
    }

    /**
     * 刷新各类认证状态过期状态定时器
     */
    //@Scheduled(fixedRate = 1000 * 3600 * 24) // 每 24小时 执行一次 （单位ms）
    @Scheduled(cron = "0 30 0 * * ?") // 每天凌晨0点30分执行
    public void refreshValidityCertificationStatusTask() {
        System.out.println("[refreshValidityCertificationStatusTask] 定时任务开始执行: " + CommonUtils.formatCurrentTime());

        coreAlgorithmService.refreshDeviceTechCapacityOverdueValidity();
        coreAlgorithmService.refreshSpecialTechCapacityOverdueValidity();
        coreAlgorithmService.refreshLineTechCapacityOverdueValidity();
        coreAlgorithmService.sendEmailsForOverdue();

        System.out.println("[refreshValidityCertificationStatusTask] 定时任务结束执行: " + CommonUtils.formatCurrentTime());
    }

    //每天 8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23点 写入
    //@Scheduled(fixedRate = 1000 * 3600 * 24)
    @Scheduled(cron = "0 0 8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23 * * ?") //
    public void saveCmAndLineAndDeviceInfoIntoTable8() {
        System.out.println("[saveCmAndLineAndDeviceInfoIntoTable8] 定时任务开始执行: " + CommonUtils.formatCurrentTime());

        try {
            Date now = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(now);
            int hour = calendar.get(Calendar.HOUR_OF_DAY); // 获取24小时制的小时

            List<PcbaCompany> allCompany = pcbaCompanyDao.getAllCompany(null, null);
            for (PcbaCompany pcbaCompany : allCompany) {
                Integer pcbaCompanyId = pcbaCompany.getPcbaCompanyId();
                List<PcbaCompany> pcbaCompanyList = thirdApiSendService.getAllCmAndLineCapacityAndDeviceCapacityCommon(pcbaCompanyId);
                Result result_s = ResultUtil.success(pcbaCompanyList);
                String result = JSON.toJSONString(result_s,SerializerFeature.DisableCircularReferenceDetect);
                List<CompanyInfo> list = companyInfoDao.getCompanyInfoByCompanyId(pcbaCompanyId);
                if(list.size() > 0){
                    String oldResult = list.get(0).getResultFirst() != null ? list.get(0).getResultFirst() : "";
                    CompanyInfo updateCompanyInfo = new CompanyInfo();
                    updateCompanyInfo.setCompanyId(pcbaCompanyId);
                    updateCompanyInfo.setResult(result);
                    updateCompanyInfo.setUpdateTime(new Date());
                    if(oldResult.equals(result)){
                        updateCompanyInfo.setIsModify(2);
                    }else{
                        updateCompanyInfo.setIsModify(1);
                    }
                    if(hour == 23){
                        updateCompanyInfo.setResultFirst(result);
                    }
                    companyInfoDao.updateCompanyInfo(updateCompanyInfo);
                }else{
                    CompanyInfo addCompanyInfo = new CompanyInfo();
                    addCompanyInfo.setCompanyId(pcbaCompanyId);
                    addCompanyInfo.setResult(result);
                    addCompanyInfo.setUpdateTime(new Date());
                    addCompanyInfo.setIsModify(2);
                    if(hour == 23){
                        addCompanyInfo.setResultFirst(result);
                        companyInfoDao.addCompanyInfo_23(addCompanyInfo);
                    }else{
                        companyInfoDao.addCompanyInfo_Not_23(addCompanyInfo);
                    }
                }
            }
            List<PcbaCompany> pcbaCompanyListAll = thirdApiSendService.getAllCmAndLineCapacityAndDeviceCapacityCommon(0);
            Result result_sAll = ResultUtil.success(pcbaCompanyListAll);
            List<CompanyInfo> listAll = companyInfoDao.getCompanyInfoByCompanyId(0);
            String result = JSON.toJSONString(result_sAll,SerializerFeature.DisableCircularReferenceDetect);
            if(listAll.size() > 0){
                String oldResult = listAll.get(0).getResultFirst() != null ? listAll.get(0).getResultFirst() : "";
                CompanyInfo updateCompanyInfo = new CompanyInfo();
                updateCompanyInfo.setCompanyId(0);
                updateCompanyInfo.setResult(result);
                updateCompanyInfo.setUpdateTime(new Date());
                if(oldResult.equals(result)){
                    updateCompanyInfo.setIsModify(2);
                }else{
                    updateCompanyInfo.setIsModify(1);
                }
                if(hour == 23){
                    updateCompanyInfo.setResultFirst(result);
                }
                companyInfoDao.updateCompanyInfo(updateCompanyInfo);
            }else{
                CompanyInfo addCompanyInfo = new CompanyInfo();
                addCompanyInfo.setCompanyId(0);
                addCompanyInfo.setResult(result);
                addCompanyInfo.setUpdateTime(new Date());
                addCompanyInfo.setIsModify(2);
                if(hour == 23){
                    addCompanyInfo.setResultFirst(result);
                    companyInfoDao.addCompanyInfo_23(addCompanyInfo);
                }else{
                    companyInfoDao.addCompanyInfo_Not_23(addCompanyInfo);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("[saveCmAndLineAndDeviceInfoIntoTable8] 定时任务结束执行: " + CommonUtils.formatCurrentTime());
    }

    /**
     * 刷新工厂信息线体信息缓存
     */
    //@Scheduled(fixedRate = 1000 * 3600 * 24) // 每 24小时 执行一次 （单位ms）
    /*@Scheduled(cron = "0 30 2 * * ?") // 每天凌晨2点30分执行
    public void saveCmAndLineAndDeviceInfoIntoRedis() {
        System.out.println("[saveCmAndLineAndDeviceInfoIntoRedis] 定时任务开始执行: " + CommonUtils.formatCurrentTime());

        try {
            List<PcbaCompany> allCompany = pcbaCompanyDao.getAllCompany(null, null);
            for (PcbaCompany pcbaCompany : allCompany) {
                Integer pcbaCompanyId = pcbaCompany.getPcbaCompanyId();
                List<PcbaCompany> pcbaCompanyList = thirdApiSendService.getAllCmAndLineCapacityAndDeviceCapacityCommon(pcbaCompanyId);
                String s = JSON.toJSONString(pcbaCompanyList);
                redisCRUD.saveCmAndLineCapacityAndDeviceCapacityInfo(pcbaCompanyId.toString(), s);
            }
            List<PcbaCompany> pcbaCompanyListAll = thirdApiSendService.getAllCmAndLineCapacityAndDeviceCapacityCommon(0);
            String sAll = JSON.toJSONString(pcbaCompanyListAll);
            redisCRUD.saveCmAndLineCapacityAndDeviceCapacityInfo("0", sAll);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("[saveCmAndLineAndDeviceInfoIntoRedis] 定时任务结束执行: " + CommonUtils.formatCurrentTime());
    }*/
    /**
     * 清除工厂信息线体信息缓存（以防有效期过了redis缓存没有清掉）
     */
    //@Scheduled(fixedRate = 1000 * 3600 * 24) // 每 24小时 执行一次 （单位ms）
    /*@Scheduled(cron = "0 30 5 * * ?") // 每天凌晨5点30分执行  清除 redis中工厂线体的缓存（以防有效期过了redis缓存没有清掉）
    public void clearCmAndLineAndDeviceInfoIntoRedis() {
        System.out.println("[clearCmAndLineAndDeviceInfoIntoRedis] 定时任务开始执行: " + CommonUtils.formatCurrentTime());

        try {
            List<PcbaCompany> allCompany = pcbaCompanyDao.getAllCompany(null, null);
            for (PcbaCompany pcbaCompany : allCompany) {
                Integer pcbaCompanyId = pcbaCompany.getPcbaCompanyId();
                if (redisTemplate.hasKey("getAllCmAndLineCapacityAndDeviceCapacity_" + pcbaCompanyId)) {
                    System.out.println("从redis缓存查询单板信息,key=" + "getAllCmAndLineCapacityAndDeviceCapacity_" + pcbaCompanyId + "->成功");
                    redisCRUD.deleteCmAndLineCapacityAndDeviceCapacityInfo(pcbaCompanyId.toString());
                }
                if (redisTemplate.hasKey("getAllCmAndLineCapacityAndDeviceCapacity_0")) {
                    System.out.println("从redis缓存查询单板信息,key=" + "getAllCmAndLineCapacityAndDeviceCapacity_" + pcbaCompanyId + "->成功");
                    redisCRUD.deleteCmAndLineCapacityAndDeviceCapacityInfo("0");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("[clearCmAndLineAndDeviceInfoIntoRedis] 定时任务结束执行: " + CommonUtils.formatCurrentTime());
    }*/

    /**
     * 定时刷新线体的最终状态(修复异常数据)
     */
    //@Scheduled(fixedRate = 1000 * 3600 * 24)
    @Scheduled(cron = "0 0 1 * * ?") // 每天凌晨1点00分执行
    public void restorePcbaLineFinalStatus() {
        System.out.println("[restorePcbaLineFinalStatus] 定时任务开始执行: " + CommonUtils.formatCurrentTime());
        try {
            coreAlgorithmService.updatePcbaLineFinalStatus(1, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("[restorePcbaLineFinalStatus] 定时任务结束执行: " + CommonUtils.formatCurrentTime());
    }

    /**
     * 自动刷新设备参数、工艺整线能力 是否参与pcba能力匹配的逻辑
     */
    @Scheduled(cron = "0 0 3 * * ?") // 每天凌晨3点执行
    //@Scheduled(fixedRate = 1000 * 3600 * 24) // 每 24小时 执行一次 （单位ms）
    public void refreshPcbaDeviceParamAndTechCapacityRuleIsRelatedPcbaTask() {
        System.out.println("[refreshPcbaDeviceParamAndTechCapacityRuleIsRelatedPcbaTask] 定时任务开始执行: " + CommonUtils.formatCurrentTime());

        thirdApiSendService.refreshPcbaDeviceParamIsRelatedPcba();
        thirdApiSendService.refreshTechDeviceParamIsRelatedPcba();
        thirdApiSendService.refreshTechCapacityRuleIsRelatedPcba();

        System.out.println("[refreshPcbaDeviceParamAndTechCapacityRuleIsRelatedPcbaTask] 定时任务结束执行: " + CommonUtils.formatCurrentTime());
    }


    /**
     * 高端线体超期设备自动发邮件
     */
    @Scheduled(cron = "0 0 1 * * ?") // 每天凌晨1点执行
    //@Scheduled(fixedRate = 1000 * 10000) // 每 10000s 执行一次
    public void autoSendEmailToDeviceOfHighLine() {
        // 执行任务
        System.out.println("[autoSendEmailToDeviceOfHighLine] 定时任务开始执行: " + CommonUtils.formatCurrentTime());

        handleDeviceOverdueSixYearsOfHighLine();
    }

    public void handleDeviceOverdueSixYearsOfHighLine() {
        try {
            // 高端线体的列表
            List<PcbaLine> highLineList = new ArrayList<>();

            List<PcbaLine> list = pcbaLineDao.getAllPcbaLineView(null, null, null, 1, 1, null, null, null);
            for (PcbaLine pcbaLine : list) {
                LineLevel lineLevel = lineLevelDao.getLineLevelById(pcbaLine.getPcbaLineLevel());
                if (lineLevel != null && lineLevel.getLineLevelName().contains("高端")) {
                    highLineList.add(pcbaLine);
                }
            }
            for (PcbaLine pcbaLine : highLineList) {
                pcbaLine.setLineLevel(lineLevelDao.getLineLevelById(pcbaLine.getPcbaLineLevel()));
                List<PcbaDevice> pcbaDeviceList = pcbaDeviceDao.getPcbaDeviceByLine(pcbaLine.getPcbaLineId());
                pcbaLine.setPcbaDeviceNums(pcbaDeviceList.size());
                pcbaLine.setPcbaDeviceList(pcbaDeviceList);
                for (PcbaDevice pcbaDevice : pcbaDeviceList) {
                    if (pcbaDevice.getProductTime() != null && !"".equals(pcbaDevice.getProductTime().toString())) {
                        Date d1 = new Date();
                        LocalDate ld1 = d1.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                        LocalDate ld2 = pcbaDevice.getProductTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                        double age = CommonUtils.calculateYearDifference(ld2, ld1);
                        pcbaDevice.setAge(age);

                        Result result = coreAlgorithmService.calcIsOverSixYearInHighLine(pcbaDevice, pcbaLine.getPcbaLineLevel());
                        if (result.getCode() == 200) {
                            int i = Integer.parseInt(result.getData().toString());
                            pcbaDevice.setIsOverSixYearInHighLine(i);
                        }
                    }
                }
//            int isOverSixYearInHighLine = 2;
//            for (PcbaDevice pcbaDevice : pcbaDeviceList) {
//                if(pcbaDevice.getIsOverSixYearInHighLine() != null && pcbaDevice.getIsOverSixYearInHighLine() == 1){
//                    isOverSixYearInHighLine = 1;
//                    break;
//                }
//            }
//            pcbaLine.setPcbaDeviceList(pcbaDeviceList);
//            pcbaLine.setIsOverSixYearInHighLine(isOverSixYearInHighLine);
            }
//        List<PcbaLine> finalList = new ArrayList<>();
//        for (PcbaLine pcbaLine : highLineList) {
//            if(pcbaLine.getIsOverSixYearInHighLine() == 1){
//                finalList.add(pcbaLine);
//            }
//        }

//        if(finalList.size() > 0){
//            String assetNumbers = "";
//            for (PcbaLine pcbaLine : finalList) {
//                for (PcbaDevice pcbaDevice : pcbaLine.getPcbaDeviceList()) {
//                    if(pcbaDevice.getIsOverSixYearInHighLine() != null && pcbaDevice.getIsOverSixYearInHighLine() == 1){
//                        assetNumbers = assetNumbers + pcbaDevice.getAssetNumber() + ";";
//                    }
//                }
//            }
//        }

            try {
            /*List<User> userList = new ArrayList<>();

            List<MaintenanceConfig> maintenanceConfigByType = maintenanceConfigDao.getMaintenanceConfigByType(5);
            if(maintenanceConfigByType.size() > 0){
                String sendEmailUsers = maintenanceConfigByType.get(0).getSendEmailUsers();
                if(sendEmailUsers != null && !"".equals(sendEmailUsers)){
                    String[] split = sendEmailUsers.split(",");
                    for (String s : split) {
                        if(s.contains("/")){
                            String[] strings = s.split("\\/");
                            if(strings.length == 2){
                                String domainAccount = strings[1];
                                if(domainAccount != null && !"".equals(domainAccount)){
                                    User u = userDao.getUserInfoByDomainAccount(domainAccount);
                                    if(u != null){
                                        userList.add(u);
                                    }
                                }
                            }
                        }
                    }
                }

            List<MailAddress> mailAddressList = new ArrayList<>();
            for (User user : userList) {
                MailAddress mailAddress = new MailAddress();
                mailAddress.setMailAddress(user.getEmail());
                mailAddress.setType(0);
                mailAddressList.add(mailAddress);
            }*/
                //System.out.println(mailAddressList);

                for (PcbaLine pcbaLine : highLineList) {

                    // 构造接收邮件人
                    List<User> userList = new ArrayList<>();
                    Integer pcbaCompanyId = pcbaLine.getPcbaCompanyId();
                    PcbaCompany pcbaCompany = pcbaCompanyDao.getPcbaCompanyById(pcbaCompanyId);
                    if (pcbaCompany != null && pcbaCompany.getEmailOwners() != null && !"".equals(pcbaCompany.getEmailOwners())) {
                        String sendEmailUsers = pcbaCompany.getEmailOwners();
                        String[] split = sendEmailUsers.split(",");
                        for (String s : split) {
                            if (s.contains("/")) {
                                String[] strings = s.split("\\/");
                                if (strings.length == 2) {
                                    String domainAccount = strings[1];
                                    if (domainAccount != null && !"".equals(domainAccount)) {
                                        User u = userDao.getUserInfoByDomainAccount(domainAccount);
                                        if (u != null) {
                                            userList.add(u);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    List<MailAddress> mailAddressList = new ArrayList<>();
                    for (User user : userList) {
                        if(user.getEmail().contains(",")){
                            String[] emailsArr = user.getEmail().split(",");
                            for (String email : emailsArr) {
                                MailAddress mailAddress = new MailAddress();
                                mailAddress.setMailAddress(email);
                                mailAddress.setType(0);
                                mailAddressList.add(mailAddress);
                            }
                        }else{
                            MailAddress mailAddress = new MailAddress();
                            mailAddress.setMailAddress(user.getEmail());
                            mailAddress.setType(0);
                            mailAddressList.add(mailAddress);
                        }
                    }

                    // 当前时间的 00：00：00
                    Date d = new Date();
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(d);
                    calendar.set(Calendar.HOUR_OF_DAY, 0); // 设置小时为 0
                    calendar.set(Calendar.MINUTE, 0);      // 设置分钟为 0
                    calendar.set(Calendar.SECOND, 0);      // 设置秒钟为 0
                    calendar.set(Calendar.MILLISECOND, 0); // 设置毫秒为 0
                    Date time = calendar.getTime();

                    if (mailAddressList.size() > 0) {
                        for (PcbaDevice pcbaDevice : pcbaLine.getPcbaDeviceList()) {

                            if("ergrthtyhtyh".equals(pcbaDevice.getAssetNumber())){
                                System.out.println("ergrthtyhtyh");
                            }

                            Integer pcbaLineId = pcbaDevice.getPcbaLineId();
                            PcbaLine pcbaLineById = pcbaLineDao.getPcbaLineById(pcbaLineId);
                            pcbaLineById.setPcbaCompany(pcbaCompanyDao.getPcbaCompanyById(pcbaLineById.getPcbaCompanyId()));
                            pcbaLineById.setPcbaWorkshop(pcbaWorkshopDao.getPcbaWorkshopById(pcbaLineById.getPcbaWorkshopId()));

                            String brandName = "";
                            String brandTypeName = "";
                            String pcbaDeviceTypeName = "";
                            PcbaDeviceResource pcbaDeviceResource = pcbaDeviceResourceDao.getById(pcbaDevice.getPcbaDeviceResourceId());
                            if(pcbaDeviceResource != null){
                                PcbaDeviceType pcbaDeviceType = pcbaDeviceTypeDao.getById(pcbaDeviceResource.getPcbaDeviceTypeId());
                                Brand brand = brandDao.getBrandById(pcbaDeviceResource.getBrandId());
                                BrandType brandType = brandTypeDao.getBrandTypeById(pcbaDeviceResource.getBrandTypeId());
                                if(pcbaDeviceType != null && pcbaDeviceType.getPcbaDeviceTypeNameCn() != null){
                                    pcbaDeviceTypeName = pcbaDeviceType.getPcbaDeviceTypeNameCn();
                                }
                                if(brand != null && brand.getBrandName() != null){
                                    brandName = brand.getBrandName();
                                }
                                if(brandType != null && brandType.getBrandTypeName() != null){
                                    brandTypeName = brandType.getBrandTypeName();
                                }
                            }

                            String mailContent1 = "<html><body>" +
                                    "<p>主题：" + DB1EmailTemplates.OVER_SIX_YEAR_IN_HIGH_LINE_CONTENT + "</p>" +
                                    "<p>标识：首次发送</p>" +
                                    "<p>设备资产编号：" + pcbaDevice.getAssetNumber() + "</p>" +
                                    "<p>设备类型：" + pcbaDeviceTypeName + "</p>" +
                                    "<p>品牌：" + brandName + "</p>" +
                                    "<p>型号：" + brandTypeName + "</p>" +
                                    "<p>所在线体：" + pcbaLineById.getPcbaCompany().getPcbaCompanyNameCn() + "/" + pcbaLineById.getPcbaWorkshop().getPcbaWorkshopNameCn() + "/" + pcbaLineById.getPcbaLineNameCn() + "</p>" +
                                    "<p>网页链接：<a href='" + trustedRedirectUri + DB1EmailTemplates.OVER_SIX_YEAR_IN_HIGH_LINE_WEB_URL + "'>点击跳转</a></p>" +
                                    "</body></html>";

                            String mailContent2 = "<html><body>" +
                                    "<p>主题：" + DB1EmailTemplates.OVER_SIX_YEAR_IN_HIGH_LINE_CONTENT + "</p>" +
                                    "<p>标识：未闭环处理，按照频次发</p>" +
                                    "<p>设备资产编号：" + pcbaDevice.getAssetNumber() + "</p>" +
                                    "<p>设备类型：" + pcbaDeviceTypeName + "</p>" +
                                    "<p>品牌：" + brandName + "</p>" +
                                    "<p>型号：" + brandTypeName + "</p>" +
                                    "<p>所在线体：" + pcbaLineById.getPcbaCompany().getPcbaCompanyNameCn() + "/" + pcbaLineById.getPcbaWorkshop().getPcbaWorkshopNameCn() + "/" + pcbaLineById.getPcbaLineNameCn() + "</p>" +
                                    "<p>网页链接：<a href='" + trustedRedirectUri + DB1EmailTemplates.OVER_SIX_YEAR_IN_HIGH_LINE_WEB_URL + "'>点击跳转</a></p>" +
                                    "</body></html>";

                            String mailContent3 = "<html><body>" +
                                    "<p>主题：" + DB1EmailTemplates.OVER_SIX_YEAR_IN_HIGH_LINE_CONTENT + "</p>" +
                                    "<p>标识：闭环处理失效，重启按照频次发</p>" +
                                    "<p>设备资产编号：" + pcbaDevice.getAssetNumber() + "</p>" +
                                    "<p>设备类型：" + pcbaDeviceTypeName + "</p>" +
                                    "<p>品牌：" + brandName + "</p>" +
                                    "<p>型号：" + brandTypeName + "</p>" +
                                    "<p>所在线体：" + pcbaLineById.getPcbaCompany().getPcbaCompanyNameCn() + "/" + pcbaLineById.getPcbaWorkshop().getPcbaWorkshopNameCn() + "/" + pcbaLineById.getPcbaLineNameCn() + "</p>" +
                                    "<p>网页链接：<a href='" + trustedRedirectUri + DB1EmailTemplates.OVER_SIX_YEAR_IN_HIGH_LINE_WEB_URL + "'>点击跳转</a></p>" +
                                    "</body></html>";

                            Date loopCloseTime = pcbaDevice.getLoopCloseTime();
                            Date loopCloseLastSendTime = pcbaDevice.getLoopCloseLastSendTime();

                            if (pcbaDevice.getIsOverSixYearInHighLine() != null && pcbaDevice.getIsOverSixYearInHighLine() == 1) {
                                Integer forewarningAgeUnDisposed = 15;
                                Integer forewarningAgeDisposed = 15;
                                List<MaintenanceConfig> m = maintenanceConfigDao.getMaintenanceConfigByType(2);
                                if (m != null && m.size() > 0) {
                                    forewarningAgeUnDisposed = m.get(0).getForewarningAgeUndisposed() != null ? m.get(0).getForewarningAgeUndisposed() : 15;
                                    forewarningAgeDisposed = m.get(0).getForewarningAgeDisposed() != null ? m.get(0).getForewarningAgeDisposed() : 15;
                                }

                                if(loopCloseTime == null && loopCloseLastSendTime == null){
                                    // 闭环处理时间 最新发邮件时间 均为空，则肯定发邮件通知
                                    Result result = thirdApiService.sendMail("", DB1EmailTemplates.OVER_SIX_YEAR_IN_HIGH_LINE_TITLE_OK, DB1EmailTemplates.OVER_SIX_YEAR_IN_HIGH_LINE_CONTENT_TITLE,
                                            mailContent1, "10086", mailAddressList, null, null, null, null, 2, null);
                                    if (result.getCode() == 200) {
                                        System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                                        System.out.println("【高端线体】设备超期定时发邮件(首次),发送成功");
                                    } else {
                                        System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                                        System.out.println("【高端线体】设备超期定时发邮件(首次),发送失败:" + result.getMsgCn());
                                    }
                                    // 更新 上次发送时间
                                    pcbaDeviceDao.updateDeviceLoopCloseLastSendTime(time, pcbaDevice.getPcbaDeviceId());
                                }
                                if(loopCloseTime == null && loopCloseLastSendTime != null){
                                    // 闭环处理时间为空 且 上次发邮件时间 不为空 则根据 上次发邮件时间 计算 天数差 来确定是否发
                                    Calendar calendar2 = Calendar.getInstance();
                                    calendar2.setTime(loopCloseLastSendTime);
                                    calendar2.set(Calendar.HOUR_OF_DAY, 0); // 设置小时为 0
                                    calendar2.set(Calendar.MINUTE, 0);      // 设置分钟为 0
                                    calendar2.set(Calendar.SECOND, 0);      // 设置秒钟为 0
                                    calendar2.set(Calendar.MILLISECOND, 0); // 设置毫秒为 0
                                    Date loopCloseLastSendTime00 = calendar2.getTime();
                                    // 计算天数差
                                    LocalDate ld1 = time.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                                    LocalDate ld2 = loopCloseLastSendTime00.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                                    double daysDiff = CommonUtils.calculateDayDifference(ld2, ld1);
                                    if(daysDiff % forewarningAgeUnDisposed == 0){
                                        Result result = thirdApiService.sendMail("", DB1EmailTemplates.OVER_SIX_YEAR_IN_HIGH_LINE_TITLE_OK, DB1EmailTemplates.OVER_SIX_YEAR_IN_HIGH_LINE_CONTENT_TITLE,
                                                mailContent2, "10086", mailAddressList, null, null, null, null, 2, null);
                                        if (result.getCode() == 200) {
                                            System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                                            System.out.println("【高端线体】设备超期定时发邮件(未闭环处理，按照频次发),发送成功");
                                        } else {
                                            System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                                            System.out.println("【高端线体】设备超期定时发邮件(未闭环处理，按照频次发),发送失败:" + result.getMsgCn());
                                        }
                                        // 更新 上次发送时间
                                        pcbaDeviceDao.updateDeviceLoopCloseLastSendTime(time, pcbaDevice.getPcbaDeviceId());
                                    }
                                }
                                if(loopCloseTime != null){
                                    // 闭环处理时间不为空 则根据 闭环处理时间 计算 天数差 来确定是否发
                                    Calendar calendar2 = Calendar.getInstance();
                                    calendar2.setTime(loopCloseTime);
                                    calendar2.set(Calendar.HOUR_OF_DAY, 0); // 设置小时为 0
                                    calendar2.set(Calendar.MINUTE, 0);      // 设置分钟为 0
                                    calendar2.set(Calendar.SECOND, 0);      // 设置秒钟为 0
                                    calendar2.set(Calendar.MILLISECOND, 0); // 设置毫秒为 0
                                    Date loopCloseTime00 = calendar2.getTime();
                                    // 计算天数差
                                    LocalDate ld1 = time.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                                    LocalDate ld2 = loopCloseTime00.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                                    double daysDiff = CommonUtils.calculateDayDifference(ld2, ld1);
                                    if(daysDiff >= forewarningAgeDisposed){
                                        if((daysDiff - forewarningAgeDisposed) % forewarningAgeUnDisposed == 0){
                                            Result result = thirdApiService.sendMail("", DB1EmailTemplates.OVER_SIX_YEAR_IN_HIGH_LINE_TITLE_OK, DB1EmailTemplates.OVER_SIX_YEAR_IN_HIGH_LINE_CONTENT_TITLE,
                                                    mailContent3, "10086", mailAddressList, null, null, null, null, 2, null);
                                            if (result.getCode() == 200) {
                                                System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                                                System.out.println("【高端线体】设备超期定时发邮件(闭环处理失效，重启按照频次发),发送成功");
                                            } else {
                                                System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                                                System.out.println("【高端线体】设备超期定时发邮件(闭环处理失效，重启按照频次发),发送失败:" + result.getMsgCn());
                                            }
                                            // 更新 上次发送时间
                                            pcbaDeviceDao.updateDeviceLoopCloseLastSendTime(time, pcbaDevice.getPcbaDeviceId());
                                        }
                                    }
                                }
                            }
//                            if (pcbaDevice.getIsOverSixYearInHighLine() != null && pcbaDevice.getIsOverSixYearInHighLine() == 3) {
//                                LocalDateTime lastExecutionDateTime = LocalDateTime.now();
//                                if (loopCloseLastSendTime != null) {
//                                    lastExecutionDateTime = loopCloseLastSendTime.toInstant()
//                                            .atZone(ZoneId.systemDefault())
//                                            .toLocalDateTime();
//
//                                }
//
//                                // 每 15 天
//                                // 计算上次执行任务的日期与当前日期之间的天数差
//                                /*long daysSinceLastExecution = ChronoUnit.DAYS.between(lastExecutionDateTime, LocalDateTime.now());*/
//                                Integer forewarningAgeDisposed = 15;
//                                List<MaintenanceConfig> m = maintenanceConfigDao.getMaintenanceConfigByType(2);
//                                if (m != null && m.size() > 0) {
//                                    forewarningAgeDisposed = m.get(0).getForewarningAgeDisposed() != null ? m.get(0).getForewarningAgeDisposed() : 15;
//                                }
//
//                                //System.out.println("daysSinceLastExecution=" + daysSinceLastExecution);
//                                //System.out.println("forewarningAgeDisposed=" + forewarningAgeDisposed);
//                                // 原先逻辑每隔15天发
//                        /*if(daysSinceLastExecution >= forewarningAgeDisposed){
//                            thirdApiService.sendMail("", DB1EmailTemplates.OVER_SIX_YEAR_IN_HIGH_LINE_TITLE_OK,DB1EmailTemplates.OVER_SIX_YEAR_IN_HIGH_LINE_CONTENT_TITLE,
//                                    DB1EmailTemplates.OVER_SIX_YEAR_IN_HIGH_LINE_CONTENT + "，设备资产编号：" + pcbaDevice.getAssetNumber(),"10086", mailAddressList,null,null,null,null,2,null);
//                            System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
//                            System.out.println("【高端线体】设备超期定时发邮件(15天),发送成功");
//                            // 更新 上次发送时间
//                            pcbaDeviceDao.updateDeviceLoopCloseLastSendTime(time, pcbaDevice.getPcbaDeviceId());
//                        }*/
//                                // 现在逻辑改为超过这么多天数继续每天发
//                                // 当前时间 >= (闭环关闭时间 + 配置挂起天数) 继续发
//                                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//                                // 将Date转换为Instant
//                                Instant instant = loopCloseTime.toInstant();
//                                // 将Instant转换为LocalDateTime
//                                LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
//                                // 加上指定天数
//                                LocalDateTime newTime = localDateTime.plusDays(forewarningAgeDisposed);
//                                long timeRangeNum = ChronoUnit.SECONDS.between(newTime, LocalDateTime.now());
//                                if (timeRangeNum > 0) {
//                                    Result result = thirdApiService.sendMail("", DB1EmailTemplates.OVER_SIX_YEAR_IN_HIGH_LINE_TITLE_OK, DB1EmailTemplates.OVER_SIX_YEAR_IN_HIGH_LINE_CONTENT_TITLE,
//                                            mailContent, "10086", mailAddressList, null, null, null, null, 2, null);
//                                    if (result.getCode() == 200) {
//                                        System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
//                                        System.out.println("【高端线体】设备超期定时发邮件(挂起处理超时后继续发送),发送成功");
//                                    } else {
//                                        System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
//                                        System.out.println("【高端线体】设备超期定时发邮件(挂起处理超时后继续发送),发送失败:" + result.getMsgCn());
//                                    }
//                                    // 更新 上次发送时间
//                                    pcbaDeviceDao.updateDeviceLoopCloseLastSendTime(time, pcbaDevice.getPcbaDeviceId());
//                                }
//                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                System.out.println("【高端线体】设备超期定时发邮件,发送失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
            System.out.println("【高端线体】设备超期定时发邮件,发送失败");
        }
    }


    /**
     * 线体设备年限预警自动发邮件
     */
    @Scheduled(cron = "0 0 1 * * ?") // 每天凌晨1点执行
    //@Scheduled(fixedRate = 1000 * 10000) // 每 10000s 执行一次
    public void autoSendEmailToDeviceForAge() {
        // 执行任务
        System.out.println("[autoSendEmailToDeviceForAge] 定时任务开始执行: " + CommonUtils.formatCurrentTime());

        handleDeviceAgeOfLine();
    }

    public void handleDeviceAgeOfLine() {
        try {
            List<MaintenanceConfig> maintenanceConfigList = maintenanceConfigDao.getMaintenanceConfigByType(1);
            if (maintenanceConfigList.size() == 3) {
                // 获取第二条和第三条的配置值
                MaintenanceConfig m2 = maintenanceConfigList.get(1);
                MaintenanceConfig m3 = maintenanceConfigList.get(2);

                // 大于以下年限（maintenanceConfigRange2_1） 且 小于等于 以下年限（maintenanceConfigRange2_2） 发送邮件
                Double maintenanceConfigRange2_1 = m2.getMaintenanceConfigRange1();
                Double maintenanceConfigRange2_2 = m2.getMaintenanceConfigRange2();
                // 未处理预警的情况下按照 forewarningAgeUndisposed2 天数 发送
                Integer forewarningAgeUndisposed2 = m2.getForewarningAgeUndisposed();
                // 已处理预警的情况下 在 forewarningAgeDisposed2 天后，继续每隔 forewarningAgeUndisposed2 天数发送
                Integer forewarningAgeDisposed2 = m2.getForewarningAgeDisposed();

                // 大于此年限（maintenanceConfigRange3_1）发送邮件
                Double maintenanceConfigRange3_1 = m3.getMaintenanceConfigRange1();
                // 未处理预警的情况下按照 forewarningAgeUndisposed3 天数 发送
                Integer forewarningAgeUndisposed3 = m3.getForewarningAgeUndisposed();
                // 已处理预警的情况下 在 forewarningAgeDisposed3 天后，继续每隔 forewarningAgeUndisposed3 天数发送
                Integer forewarningAgeDisposed3 = m3.getForewarningAgeDisposed();

                List<PcbaLine> list = pcbaLineDao.getAllPcbaLineView(null, null, null, 1, 1, null, null, null);

                // 当前时间的 00：00：00
                Date d = new Date();
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(d);
                calendar.set(Calendar.HOUR_OF_DAY, 0); // 设置小时为 0
                calendar.set(Calendar.MINUTE, 0);      // 设置分钟为 0
                calendar.set(Calendar.SECOND, 0);      // 设置秒钟为 0
                calendar.set(Calendar.MILLISECOND, 0); // 设置毫秒为 0
                Date time = calendar.getTime();

                for (PcbaLine pcbaLine : list) {
                    // 仅SMT线体发
                    if(pcbaLine.getPcbaLineType() == 1){
                        pcbaLine.setLineLevel(lineLevelDao.getLineLevelById(pcbaLine.getPcbaLineLevel()));
                        List<PcbaDevice> pcbaDeviceList = pcbaDeviceDao.getPcbaDeviceByLine(pcbaLine.getPcbaLineId());
                        pcbaLine.setPcbaDeviceNums(pcbaDeviceList.size());
                        pcbaLine.setPcbaDeviceList(pcbaDeviceList);
                        for (PcbaDevice pcbaDevice : pcbaDeviceList) {
                            if (pcbaDevice.getProductTime() != null && !"".equals(pcbaDevice.getProductTime().toString())) {
                                Date d1 = new Date();
                                LocalDate ld11 = d1.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                                LocalDate ld22 = pcbaDevice.getProductTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                                double age = CommonUtils.calculateYearDifference(ld22, ld11);
                                pcbaDevice.setAge(age);

                                Result res = coreAlgorithmService.calcIsAgeOverdueInLine(pcbaDevice);
                                if (res.getCode() == 200) {
                                    int i = Integer.parseInt(res.getData().toString());
                                    pcbaDevice.setIsHasAgeOverdueInLine(i);
                                }

                                // 构造接收邮件人
                                List<User> userList = new ArrayList<>();
                                Integer pcbaCompanyId = pcbaLine.getPcbaCompanyId();
                                Integer pcbaWorkshopId = pcbaLine.getPcbaWorkshopId();
                                PcbaCompany pcbaCompany = pcbaCompanyDao.getPcbaCompanyById(pcbaCompanyId);
                                PcbaWorkshop pcbaWorkshop = pcbaWorkshopDao.getPcbaWorkshopById(pcbaWorkshopId);
                                if (pcbaCompany != null && pcbaCompany.getEmailOwners2() != null && !"".equals(pcbaCompany.getEmailOwners2())) {
                                    String sendEmailUsers2 = pcbaCompany.getEmailOwners2();
                                    String[] split = sendEmailUsers2.split(",");
                                    for (String s : split) {
                                        if (s.contains("/")) {
                                            String[] strings = s.split("\\/");
                                            if (strings.length == 2) {
                                                String domainAccount = strings[1];
                                                if (domainAccount != null && !"".equals(domainAccount)) {
                                                    User u = userDao.getUserInfoByDomainAccount(domainAccount);
                                                    if (u != null) {
                                                        userList.add(u);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                List<MailAddress> mailAddressList = new ArrayList<>();
                                for (User user : userList) {
                                    if(user.getEmail().contains(",")){
                                        String[] emailsArr = user.getEmail().split(",");
                                        for (String email : emailsArr) {
                                            MailAddress mailAddress = new MailAddress();
                                            mailAddress.setMailAddress(email);
                                            mailAddress.setType(0);
                                            mailAddressList.add(mailAddress);
                                        }
                                    }else{
                                        MailAddress mailAddress = new MailAddress();
                                        mailAddress.setMailAddress(user.getEmail());
                                        mailAddress.setType(0);
                                        mailAddressList.add(mailAddress);
                                    }
                                }

                                if("gbf".equals(pcbaDevice.getAssetNumber())){
                                    System.out.println("gbf");
                                }
                                if("12324534523".equals(pcbaDevice.getAssetNumber())){
                                    System.out.println("12324534523");
                                }
                                if("ergrthtyhtyh".equals(pcbaDevice.getAssetNumber())){
                                    System.out.println("ergrthtyhtyh");
                                }

                                String brandName = "";
                                String brandTypeName = "";
                                String pcbaDeviceTypeName = "";
                                PcbaDeviceResource pcbaDeviceResource = pcbaDeviceResourceDao.getById(pcbaDevice.getPcbaDeviceResourceId());
                                if(pcbaDeviceResource != null){
                                    PcbaDeviceType pcbaDeviceType = pcbaDeviceTypeDao.getById(pcbaDeviceResource.getPcbaDeviceTypeId());
                                    Brand brand = brandDao.getBrandById(pcbaDeviceResource.getBrandId());
                                    BrandType brandType = brandTypeDao.getBrandTypeById(pcbaDeviceResource.getBrandTypeId());
                                    if(pcbaDeviceType != null && pcbaDeviceType.getPcbaDeviceTypeNameCn() != null){
                                        pcbaDeviceTypeName = pcbaDeviceType.getPcbaDeviceTypeNameCn();
                                    }
                                    if(brand != null && brand.getBrandName() != null){
                                        brandName = brand.getBrandName();
                                    }
                                    if(brandType != null && brandType.getBrandTypeName() != null){
                                        brandTypeName = brandType.getBrandTypeName();
                                    }
                                }

                                String mailContent1_1 = "<html><body>" +
                                        "<p>主题：" + DB1EmailTemplates.DEVICE_AGE_OF_LINE_CONTENT + "</p>" +
                                        "<p>标识：黄灯首次发送</p>" +
                                        "<p>设备资产编号：" + pcbaDevice.getAssetNumber() + "</p>" +
                                        "<p>设备类型：" + pcbaDeviceTypeName + "</p>" +
                                        "<p>品牌：" + brandName + "</p>" +
                                        "<p>型号：" + brandTypeName + "</p>" +
                                        "<p>所在线体：" + pcbaCompany.getPcbaCompanyNameCn() + "/" + pcbaWorkshop.getPcbaWorkshopNameCn() + "/" + pcbaLine.getPcbaLineNameCn() + "</p>" +
                                        "<p>网页链接：<a href='" + trustedRedirectUri + DB1EmailTemplates.DEVICE_AGE_OF_LINE_CONTENT_WEB_URL + "'>点击跳转</a></p>" +
                                        "</body></html>";
                                String mailContent1_2 = "<html><body>" +
                                        "<p>主题：" + DB1EmailTemplates.DEVICE_AGE_OF_LINE_CONTENT + "</p>" +
                                        "<p>标识：红灯首次发送</p>" +
                                        "<p>设备资产编号：" + pcbaDevice.getAssetNumber() + "</p>" +
                                        "<p>设备类型：" + pcbaDeviceTypeName + "</p>" +
                                        "<p>品牌：" + brandName + "</p>" +
                                        "<p>型号：" + brandTypeName + "</p>" +
                                        "<p>所在线体：" + pcbaCompany.getPcbaCompanyNameCn() + "/" + pcbaWorkshop.getPcbaWorkshopNameCn() + "/" + pcbaLine.getPcbaLineNameCn() + "</p>" +
                                        "<p>网页链接：<a href='" + trustedRedirectUri + DB1EmailTemplates.DEVICE_AGE_OF_LINE_CONTENT_WEB_URL + "'>点击跳转</a></p>" +
                                        "</body></html>";
                                String mailContent2_1 = "<html><body>" +
                                        "<p>主题：" + DB1EmailTemplates.DEVICE_AGE_OF_LINE_CONTENT + "</p>" +
                                        "<p>标识：黄灯未闭环处理，按照黄灯频次发</p>" +
                                        "<p>设备资产编号：" + pcbaDevice.getAssetNumber() + "</p>" +
                                        "<p>设备类型：" + pcbaDeviceTypeName + "</p>" +
                                        "<p>品牌：" + brandName + "</p>" +
                                        "<p>型号：" + brandTypeName + "</p>" +
                                        "<p>所在线体：" + pcbaCompany.getPcbaCompanyNameCn() + "/" + pcbaWorkshop.getPcbaWorkshopNameCn() + "/" + pcbaLine.getPcbaLineNameCn() + "</p>" +
                                        "<p>网页链接：<a href='" + trustedRedirectUri + DB1EmailTemplates.DEVICE_AGE_OF_LINE_CONTENT_WEB_URL + "'>点击跳转</a></p>" +
                                        "</body></html>";
                                String mailContent2_2 = "<html><body>" +
                                        "<p>主题：" + DB1EmailTemplates.DEVICE_AGE_OF_LINE_CONTENT + "</p>" +
                                        "<p>标识：红灯未闭环处理，按照红灯频次发</p>" +
                                        "<p>设备资产编号：" + pcbaDevice.getAssetNumber() + "</p>" +
                                        "<p>设备类型：" + pcbaDeviceTypeName + "</p>" +
                                        "<p>品牌：" + brandName + "</p>" +
                                        "<p>型号：" + brandTypeName + "</p>" +
                                        "<p>所在线体：" + pcbaCompany.getPcbaCompanyNameCn() + "/" + pcbaWorkshop.getPcbaWorkshopNameCn() + "/" + pcbaLine.getPcbaLineNameCn() + "</p>" +
                                        "<p>网页链接：<a href='" + trustedRedirectUri + DB1EmailTemplates.DEVICE_AGE_OF_LINE_CONTENT_WEB_URL + "'>点击跳转</a></p>" +
                                        "</body></html>";
                                String mailContent3_1 = "<html><body>" +
                                        "<p>主题：" + DB1EmailTemplates.DEVICE_AGE_OF_LINE_CONTENT + "</p>" +
                                        "<p>标识：黄灯处理超期，重启按照黄灯频次发</p>" +
                                        "<p>设备资产编号：" + pcbaDevice.getAssetNumber() + "</p>" +
                                        "<p>设备类型：" + pcbaDeviceTypeName + "</p>" +
                                        "<p>品牌：" + brandName + "</p>" +
                                        "<p>型号：" + brandTypeName + "</p>" +
                                        "<p>所在线体：" + pcbaCompany.getPcbaCompanyNameCn() + "/" + pcbaWorkshop.getPcbaWorkshopNameCn() + "/" + pcbaLine.getPcbaLineNameCn() + "</p>" +
                                        "<p>网页链接：<a href='" + trustedRedirectUri + DB1EmailTemplates.DEVICE_AGE_OF_LINE_CONTENT_WEB_URL + "'>点击跳转</a></p>" +
                                        "</body></html>";
                                String mailContent3_2 = "<html><body>" +
                                        "<p>主题：" + DB1EmailTemplates.DEVICE_AGE_OF_LINE_CONTENT + "</p>" +
                                        "<p>标识：红灯处理超期，重启按照红灯频次发</p>" +
                                        "<p>设备资产编号：" + pcbaDevice.getAssetNumber() + "</p>" +
                                        "<p>设备类型：" + pcbaDeviceTypeName + "</p>" +
                                        "<p>品牌：" + brandName + "</p>" +
                                        "<p>型号：" + brandTypeName + "</p>" +
                                        "<p>所在线体：" + pcbaCompany.getPcbaCompanyNameCn() + "/" + pcbaWorkshop.getPcbaWorkshopNameCn() + "/" + pcbaLine.getPcbaLineNameCn() + "</p>" +
                                        "<p>网页链接：<a href='" + trustedRedirectUri + DB1EmailTemplates.DEVICE_AGE_OF_LINE_CONTENT_WEB_URL + "'>点击跳转</a></p>" +
                                        "</body></html>";
                                String mailContent4 =  "<html><body>" +
                                        "<p>主题：" + DB1EmailTemplates.DEVICE_AGE_OF_LINE_CONTENT + "</p>" +
                                        "<p>标识：极端情况：黄灯挂起有效期但设备年限刚好到达红灯，按照红灯首次发</p>" +
                                        "<p>设备资产编号：" + pcbaDevice.getAssetNumber() + "</p>" +
                                        "<p>设备类型：" + pcbaDeviceTypeName + "</p>" +
                                        "<p>品牌：" + brandName + "</p>" +
                                        "<p>型号：" + brandTypeName + "</p>" +
                                        "<p>所在线体：" + pcbaCompany.getPcbaCompanyNameCn() + "/" + pcbaWorkshop.getPcbaWorkshopNameCn() + "/" + pcbaLine.getPcbaLineNameCn() + "</p>" +
                                        "<p>网页链接：<a href='" + trustedRedirectUri + DB1EmailTemplates.DEVICE_AGE_OF_LINE_CONTENT_WEB_URL + "'>点击跳转</a></p>" +
                                        "</body></html>";
                                Date ageCloseTime = pcbaDevice.getAgeCloseTime();
                                Date ageCloseLastSendTime = pcbaDevice.getAgeCloseLastSendTime();
                                Integer ageCloseFlag = pcbaDevice.getAgeCloseFlag();

                                if(mailAddressList.size() > 0){
                                    if (pcbaDevice.getIsHasAgeOverdueInLine() != null && pcbaDevice.getIsHasAgeOverdueInLine() == 1) {
                                        if(ageCloseTime == null && ageCloseLastSendTime == null){
                                            // 首次发
                                            if(age > maintenanceConfigRange2_1 && age <= maintenanceConfigRange2_2){
                                                Result result = thirdApiService.sendMail("", DB1EmailTemplates.DEVICE_AGE_OF_LINE_TITLE_OK, DB1EmailTemplates.DEVICE_AGE_OF_LINE_CONTENT_TITLE,
                                                        mailContent1_1, "10086", mailAddressList, null, null, null, null, 2, null);
                                                if (result.getCode() == 200) {
                                                    System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                                                    System.out.println("【设备年限】设备年限预警定时发邮件(黄灯首次发),发送成功");
                                                } else {
                                                    System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                                                    System.out.println("【设备年限】设备年限预警定时发邮件(黄灯首次发),发送失败:" + result.getMsgCn());
                                                }
                                                // 更新 上次发送时间
                                                pcbaDeviceDao.updateDeviceAgeCloseLastSendTime(time, pcbaDevice.getPcbaDeviceId());
                                            }
                                            if(age > maintenanceConfigRange3_1){
                                                Result result = thirdApiService.sendMail("", DB1EmailTemplates.DEVICE_AGE_OF_LINE_TITLE_OK, DB1EmailTemplates.DEVICE_AGE_OF_LINE_CONTENT_TITLE,
                                                        mailContent1_2, "10086", mailAddressList, null, null, null, null, 2, null);
                                                if (result.getCode() == 200) {
                                                    System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                                                    System.out.println("【设备年限】设备年限预警定时发邮件(红灯首次发),发送成功");
                                                } else {
                                                    System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                                                    System.out.println("【设备年限】设备年限预警定时发邮件(红灯首次发),发送失败:" + result.getMsgCn());
                                                }
                                                // 更新 上次发送时间
                                                pcbaDeviceDao.updateDeviceAgeCloseLastSendTime(time, pcbaDevice.getPcbaDeviceId());
                                            }
                                        }
                                        if(ageCloseTime == null && ageCloseLastSendTime != null){
                                            // 闭环处理时间为空 且 上次发邮件时间 不为空 则根据 上次发邮件时间 计算 天数差 来确定是否发
                                            if(age > maintenanceConfigRange2_1 && age <= maintenanceConfigRange2_2){
                                                Calendar calendar2 = Calendar.getInstance();
                                                calendar2.setTime(ageCloseLastSendTime);
                                                calendar2.set(Calendar.HOUR_OF_DAY, 0); // 设置小时为 0
                                                calendar2.set(Calendar.MINUTE, 0);      // 设置分钟为 0
                                                calendar2.set(Calendar.SECOND, 0);      // 设置秒钟为 0
                                                calendar2.set(Calendar.MILLISECOND, 0); // 设置毫秒为 0
                                                Date ageCloseLastSendTime00 = calendar2.getTime();
                                                // 计算天数差
                                                LocalDate ld1 = time.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                                                LocalDate ld2 = ageCloseLastSendTime00.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                                                double daysDiff = CommonUtils.calculateDayDifference(ld2, ld1);
                                                if(daysDiff % forewarningAgeUndisposed2 == 0){
                                                    Result result = thirdApiService.sendMail("", DB1EmailTemplates.DEVICE_AGE_OF_LINE_TITLE_OK, DB1EmailTemplates.DEVICE_AGE_OF_LINE_CONTENT_TITLE,
                                                            mailContent2_1, "10086", mailAddressList, null, null, null, null, 2, null);
                                                    if (result.getCode() == 200) {
                                                        System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                                                        System.out.println("【设备年限】设备年限预警定时发邮件(黄灯未处理，按照黄灯频次发),发送成功");
                                                    } else {
                                                        System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                                                        System.out.println("【设备年限】设备年限预警定时发邮件(黄灯未处理，按照黄灯频次发),发送失败:" + result.getMsgCn());
                                                    }
                                                    // 更新 上次发送时间
                                                    pcbaDeviceDao.updateDeviceAgeCloseLastSendTime(time, pcbaDevice.getPcbaDeviceId());
                                                }
                                            }
                                            if(age > maintenanceConfigRange3_1){
                                                Calendar calendar2 = Calendar.getInstance();
                                                calendar2.setTime(ageCloseLastSendTime);
                                                calendar2.set(Calendar.HOUR_OF_DAY, 0); // 设置小时为 0
                                                calendar2.set(Calendar.MINUTE, 0);      // 设置分钟为 0
                                                calendar2.set(Calendar.SECOND, 0);      // 设置秒钟为 0
                                                calendar2.set(Calendar.MILLISECOND, 0); // 设置毫秒为 0
                                                Date ageCloseLastSendTime00 = calendar2.getTime();
                                                // 计算天数差
                                                LocalDate ld1 = time.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                                                LocalDate ld2 = ageCloseLastSendTime00.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                                                double daysDiff = CommonUtils.calculateDayDifference(ld2, ld1);
                                                if(daysDiff % forewarningAgeUndisposed3 == 0){
                                                    Result result = thirdApiService.sendMail("", DB1EmailTemplates.DEVICE_AGE_OF_LINE_TITLE_OK, DB1EmailTemplates.DEVICE_AGE_OF_LINE_CONTENT_TITLE,
                                                            mailContent2_2, "10086", mailAddressList, null, null, null, null, 2, null);
                                                    if (result.getCode() == 200) {
                                                        System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                                                        System.out.println("【设备年限】设备年限预警定时发邮件(红灯未处理，按照红灯频次发),发送成功");
                                                    } else {
                                                        System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                                                        System.out.println("【设备年限】设备年限预警定时发邮件(红灯未处理，按照红灯频次发),发送失败:" + result.getMsgCn());
                                                    }
                                                    // 更新 上次发送时间
                                                    pcbaDeviceDao.updateDeviceAgeCloseLastSendTime(time, pcbaDevice.getPcbaDeviceId());
                                                }
                                            }
                                        }
                                        if(ageCloseTime != null){
                                            // 闭环处理时间不为空 则根据 闭环处理时间 计算 天数差 来确定是否发
                                            if(age > maintenanceConfigRange2_1 && age <= maintenanceConfigRange2_2){
                                                Calendar calendar2 = Calendar.getInstance();
                                                calendar2.setTime(ageCloseTime);
                                                calendar2.set(Calendar.HOUR_OF_DAY, 0); // 设置小时为 0
                                                calendar2.set(Calendar.MINUTE, 0);      // 设置分钟为 0
                                                calendar2.set(Calendar.SECOND, 0);      // 设置秒钟为 0
                                                calendar2.set(Calendar.MILLISECOND, 0); // 设置毫秒为 0
                                                Date ageCloseTime00 = calendar2.getTime();
                                                // 计算天数差
                                                LocalDate ld1 = time.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                                                LocalDate ld2 = ageCloseTime00.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                                                double daysDiff = CommonUtils.calculateDayDifference(ld2, ld1);
                                                if(daysDiff >= forewarningAgeDisposed2){
                                                    if((daysDiff - forewarningAgeDisposed2) % forewarningAgeUndisposed2 == 0){
                                                        Result result = thirdApiService.sendMail("", DB1EmailTemplates.DEVICE_AGE_OF_LINE_TITLE_OK, DB1EmailTemplates.DEVICE_AGE_OF_LINE_CONTENT_TITLE,
                                                                mailContent3_1, "10086", mailAddressList, null, null, null, null, 2, null);
                                                        if (result.getCode() == 200) {
                                                            System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                                                            System.out.println("【设备年限】设备年限预警定时发邮件(黄灯挂起超期，重启按照黄灯频次发),发送成功");
                                                        } else {
                                                            System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                                                            System.out.println("【设备年限】设备年限预警定时发邮件(黄灯挂起超期，重启按照黄灯频次发),发送失败:" + result.getMsgCn());
                                                        }
                                                        // 更新 上次发送时间
                                                        pcbaDeviceDao.updateDeviceAgeCloseLastSendTime(time, pcbaDevice.getPcbaDeviceId());
                                                    }
                                                }
                                            }
                                            if(age > maintenanceConfigRange3_1){
                                                Calendar calendar2 = Calendar.getInstance();
                                                calendar2.setTime(ageCloseTime);
                                                calendar2.set(Calendar.HOUR_OF_DAY, 0); // 设置小时为 0
                                                calendar2.set(Calendar.MINUTE, 0);      // 设置分钟为 0
                                                calendar2.set(Calendar.SECOND, 0);      // 设置秒钟为 0
                                                calendar2.set(Calendar.MILLISECOND, 0); // 设置毫秒为 0
                                                Date ageCloseTime00 = calendar2.getTime();
                                                // 计算天数差
                                                LocalDate ld1 = time.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                                                LocalDate ld2 = ageCloseTime00.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                                                double daysDiff = CommonUtils.calculateDayDifference(ld2, ld1);
                                                if(daysDiff >= forewarningAgeDisposed3){
                                                    if((daysDiff - forewarningAgeDisposed3) % forewarningAgeUndisposed3 == 0){
                                                        Result result = thirdApiService.sendMail("", DB1EmailTemplates.DEVICE_AGE_OF_LINE_TITLE_OK, DB1EmailTemplates.DEVICE_AGE_OF_LINE_CONTENT_TITLE,
                                                                mailContent3_2, "10086", mailAddressList, null, null, null, null, 2, null);
                                                        if (result.getCode() == 200) {
                                                            System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                                                            System.out.println("【设备年限】设备年限预警定时发邮件(红灯挂起超期，重启按照红灯频次发),发送成功");
                                                        } else {
                                                            System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                                                            System.out.println("【设备年限】设备年限预警定时发邮件(红灯挂起超期，重启按照红灯频次发),发送失败:" + result.getMsgCn());
                                                        }
                                                        // 更新 上次发送时间
                                                        pcbaDeviceDao.updateDeviceAgeCloseLastSendTime(time, pcbaDevice.getPcbaDeviceId());
                                                    }
                                                }else{
                                                    // 这里添加一个 极端情况 ，设备年限到了红灯，但是设备的挂起状态在有效期
                                                    if(ageCloseFlag == 1){
                                                        Result result = thirdApiService.sendMail("", DB1EmailTemplates.DEVICE_AGE_OF_LINE_TITLE_OK, DB1EmailTemplates.DEVICE_AGE_OF_LINE_CONTENT_TITLE,
                                                                mailContent4, "10086", mailAddressList, null, null, null, null, 2, null);
                                                        if (result.getCode() == 200) {
                                                            System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                                                            System.out.println("【设备年限】设备年限预警定时发邮件(极端情况：黄灯挂起有效期但设备年限刚好到达红灯，按照红灯首次发),发送成功");
                                                        } else {
                                                            System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                                                            System.out.println("【设备年限】设备年限预警定时发邮件(极端情况：黄灯挂起有效期但设备年限刚好到达红灯，按照红灯首次发),发送失败:" + result.getMsgCn());
                                                        }
                                                        // 更新 上次发送时间
                                                        pcbaDeviceDao.updateDeviceAgeCloseLastSendTime(time, pcbaDevice.getPcbaDeviceId());
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }




//                                if (age > maintenanceConfigRange2_1 && age <= maintenanceConfigRange2_2) {
//                                    if (mailAddressList.size() > 0) {
//                                        // 获取处理时间
//                                        Date ageCloseTime = pcbaDevice.getAgeCloseTime();
//                                        // 获取处理状态
//                                        Integer ageCloseStatus = pcbaDevice.getAgeCloseStatus();
//                                        // 获取上次发送的时间
//                                        Date ageCloseLastSendTime = pcbaDevice.getAgeCloseLastSendTime();
//                                        // 获取处理的设备预警标识  1或者null就是黄灯预警      2就是红灯预警
//                                        Integer ageCloseFlag = pcbaDevice.getAgeCloseFlag();
//                                        /**
//                                         * 构造设备年限是否已处理，
//                                         *  1.处理状态ageCloseStatus 不等于1的情况下一律判定为未处理
//                                         *  2.处理状态ageCloseStatus = 1的情况下 需要结合 处理时间 ageCloseTime ，
//                                         *    如果 当前时间 >= (处理时间 + 未处理时发送的天数配置) 则结合上次发送邮件的时间 按照未处理的频次 进行发送，否则按照已处理的频次发送
//                                         */
//                                        if (ageCloseLastSendTime != null) {
//                                            // 计算是否已处理
//                                            Boolean isHandledFlag = false;
//                                            if (ageCloseStatus == null || ageCloseStatus != 1) {
//                                                isHandledFlag = false;
//                                            } else {
//                                                Instant instant = ageCloseTime.toInstant();
//                                                LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
//                                                LocalDateTime newTime = localDateTime.plusDays(forewarningAgeUndisposed2);
//                                                long timeRangeNum = ChronoUnit.SECONDS.between(newTime, LocalDateTime.now());
//                                                if (timeRangeNum >= 0) {
//                                                    isHandledFlag = false;
//                                                } else {
//                                                    isHandledFlag = true;
//                                                }
//                                            }
//                                            if (isHandledFlag) {
//                                                // 按照已处理的频率发送
//                                                // 已处理的还要判断下 ageCloseFlag 如果 ageCloseFlag = 2，则正常走，否则 清除所有的 挂起状态 并发邮件
//                                                //if (ageCloseFlag != null && ageCloseFlag == 2) {
//                                                Instant instant = ageCloseLastSendTime.toInstant();
//                                                LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
//                                                LocalDateTime newTime = localDateTime.plusDays(forewarningAgeDisposed2);
//                                                long timeRangeNum = ChronoUnit.SECONDS.between(newTime, LocalDateTime.now());
//                                                if (timeRangeNum > 0) {
//                                                    Result result = thirdApiService.sendMail("", DB1EmailTemplates.DEVICE_AGE_OF_LINE_TITLE_OK, DB1EmailTemplates.DEVICE_AGE_OF_LINE_CONTENT_TITLE,
//                                                            mailContent, "10086", mailAddressList, null, null, null, null, 2, null);
//                                                    if (result.getCode() == 200) {
//                                                        System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
//                                                        System.out.println("【设备年限】设备年限预警定时发邮件(未处理或处理已超时),发送成功");
//                                                    } else {
//                                                        System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
//                                                        System.out.println("【设备年限】设备年限预警定时发邮件(未处理或处理已超时),发送失败:" + result.getMsgCn());
//                                                    }
//                                                    // 更新 上次发送时间
//                                                    pcbaDeviceDao.updateDeviceAgeCloseLastSendTime(time, pcbaDevice.getPcbaDeviceId());
//                                                }
//                                                //} else {
//                                                // 清除所有的 挂起状态 并发邮件
//                                                //pcbaDeviceDao.clearDeviceAgeCloseStatus(pcbaDevice.getPcbaDeviceId());
////                                                Result result = thirdApiService.sendMail("", DB1EmailTemplates.DEVICE_AGE_OF_LINE_TITLE_OK, DB1EmailTemplates.DEVICE_AGE_OF_LINE_CONTENT_TITLE,
////                                                        mailContent, "10086", mailAddressList, null, null, null, null, 2, null);
////                                                if (result.getCode() == 200) {
////                                                    System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
////                                                    System.out.println("【设备年限】设备年限预警定时发邮件(临界值，挂起状态是黄灯->红灯)),发送成功");
////                                                } else {
////                                                    System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
////                                                    System.out.println("【设备年限】设备年限预警定时发邮件(临界值，挂起状态是黄灯->红灯)),发送失败:" + result.getMsgCn());
////                                                }
////                                                // 更新 上次发送时间
////                                                pcbaDeviceDao.updateDeviceAgeCloseLastSendTime(time, pcbaDevice.getPcbaDeviceId());
//                                                //}
//                                            } else {
//                                                // 按照未处理的频率发送
////                                            Instant instant = ageCloseLastSendTime.toInstant();
////                                            LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
////                                            LocalDateTime newTime = localDateTime.plusDays(forewarningAgeUndisposed2);
////                                            long timeRangeNum = ChronoUnit.SECONDS.between(newTime, LocalDateTime.now());
////                                            if (timeRangeNum > 0) {
//                                                Result result = thirdApiService.sendMail("", DB1EmailTemplates.DEVICE_AGE_OF_LINE_TITLE_OK, DB1EmailTemplates.DEVICE_AGE_OF_LINE_CONTENT_TITLE,
//                                                        mailContent, "10086", mailAddressList, null, null, null, null, 2, null);
//                                                if (result.getCode() == 200) {
//                                                    System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
//                                                    System.out.println("【设备年限】设备年限预警定时发邮件(未处理或处理已超时),发送成功");
//                                                } else {
//                                                    System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
//                                                    System.out.println("【设备年限】设备年限预警定时发邮件(未处理或处理已超时),发送失败:" + result.getMsgCn());
//                                                }
//                                                // 更新 上次发送时间
//                                                pcbaDeviceDao.updateDeviceAgeCloseLastSendTime(time, pcbaDevice.getPcbaDeviceId());
////                                            }
//                                            }
//
//                                        } else {
//                                            // 第一次发送，直接发，记录下发送时间
//                                            Result result = thirdApiService.sendMail("", DB1EmailTemplates.DEVICE_AGE_OF_LINE_TITLE_OK, DB1EmailTemplates.DEVICE_AGE_OF_LINE_CONTENT_TITLE,
//                                                    mailContent, "10086", mailAddressList, null, null, null, null, 2, null);
//                                            if (result.getCode() == 200) {
//                                                System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
//                                                System.out.println("【设备年限】设备年限预警定时发邮件(未处理),发送成功");
//                                            } else {
//                                                System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
//                                                System.out.println("【设备年限】设备年限预警定时发邮件(未处理),发送失败:" + result.getMsgCn());
//                                            }
//                                            // 更新 上次发送时间
//                                            pcbaDeviceDao.updateDeviceAgeCloseLastSendTime(time, pcbaDevice.getPcbaDeviceId());
//                                        }
//                                    }
//                                }
//                                if (age > maintenanceConfigRange3_1) {
//                                    if (mailAddressList.size() > 0) {
//                                        // 获取处理时间
//                                        Date ageCloseTime = pcbaDevice.getAgeCloseTime();
//                                        // 获取处理状态
//                                        Integer ageCloseStatus = pcbaDevice.getAgeCloseStatus();
//                                        // 获取上次发送的时间
//                                        Date ageCloseLastSendTime = pcbaDevice.getAgeCloseLastSendTime();
//                                        /**
//                                         * 构造设备年限是否已处理，
//                                         *  1.处理状态ageCloseStatus 不等于1的情况下一律判定为未处理
//                                         *  2.处理状态ageCloseStatus = 1的情况下 需要结合 处理时间 ageCloseTime ，
//                                         *    如果 当前时间 >= (处理时间 + 未处理时发送的天数配置) 则结合上次发送邮件的时间 按照未处理的频次 进行发送，否则按照已处理的频次发送
//                                         */
//                                        if (ageCloseLastSendTime != null) {
//                                            // 计算是否已处理
//                                            Boolean isHandledFlag = false;
//                                            if (ageCloseStatus == null || ageCloseStatus != 1) {
//                                                isHandledFlag = false;
//                                            } else {
//                                                Instant instant = ageCloseTime.toInstant();
//                                                LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
//                                                LocalDateTime newTime = localDateTime.plusDays(forewarningAgeUndisposed3);
//                                                long timeRangeNum = ChronoUnit.SECONDS.between(newTime, LocalDateTime.now());
//                                                System.out.println();
//                                                if (timeRangeNum >= 0) {
//                                                    isHandledFlag = false;
//                                                } else {
//                                                    isHandledFlag = true;
//                                                }
//                                            }
//                                            if (isHandledFlag) {
//                                                // 按照已处理的频率发送
//                                                Instant instant = ageCloseLastSendTime.toInstant();
//                                                LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
//                                                LocalDateTime newTime = localDateTime.plusDays(forewarningAgeDisposed3);
//                                                long timeRangeNum = ChronoUnit.SECONDS.between(newTime, LocalDateTime.now());
//                                                if (timeRangeNum > 0) {
//                                                    Result result = thirdApiService.sendMail("", DB1EmailTemplates.DEVICE_AGE_OF_LINE_TITLE_OK, DB1EmailTemplates.DEVICE_AGE_OF_LINE_CONTENT_TITLE,
//                                                            mailContent, "10086", mailAddressList, null, null, null, null, 2, null);
//                                                    if (result.getCode() == 200) {
//                                                        System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
//                                                        System.out.println("【设备年限】设备年限预警定时发邮件(未处理或处理已超时),发送成功");
//                                                    } else {
//                                                        System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
//                                                        System.out.println("【设备年限】设备年限预警定时发邮件(未处理或处理已超时),发送失败:" + result.getMsgCn());
//                                                    }
//                                                    // 更新 上次发送时间
//                                                    pcbaDeviceDao.updateDeviceAgeCloseLastSendTime(time, pcbaDevice.getPcbaDeviceId());
//                                                }
//                                            } else {
//                                                // 按照未处理的频率发送
////                                            Instant instant = ageCloseLastSendTime.toInstant();
////                                            LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
////                                            LocalDateTime newTime = localDateTime.plusDays(forewarningAgeUndisposed3);
////                                            long timeRangeNum = ChronoUnit.SECONDS.between(newTime, LocalDateTime.now());
////                                            if (timeRangeNum > 0) {
//                                                Result result = thirdApiService.sendMail("", DB1EmailTemplates.DEVICE_AGE_OF_LINE_TITLE_OK, DB1EmailTemplates.DEVICE_AGE_OF_LINE_CONTENT_TITLE,
//                                                        mailContent, "10086", mailAddressList, null, null, null, null, 2, null);
//                                                if (result.getCode() == 200) {
//                                                    System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
//                                                    System.out.println("【设备年限】设备年限预警定时发邮件(未处理或处理已超时),发送成功");
//                                                } else {
//                                                    System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
//                                                    System.out.println("【设备年限】设备年限预警定时发邮件(未处理或处理已超时),发送失败:" + result.getMsgCn());
//                                                }
//                                                // 更新 上次发送时间
//                                                pcbaDeviceDao.updateDeviceAgeCloseLastSendTime(time, pcbaDevice.getPcbaDeviceId());
////                                            }
//                                            }
//
//                                        } else {
//                                            // 第一次发送，直接发，记录下发送时间
//                                            Result result = thirdApiService.sendMail("", DB1EmailTemplates.DEVICE_AGE_OF_LINE_TITLE_OK, DB1EmailTemplates.DEVICE_AGE_OF_LINE_CONTENT_TITLE,
//                                                    mailContent, "10086", mailAddressList, null, null, null, null, 2, null);
//                                            if (result.getCode() == 200) {
//                                                System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
//                                                System.out.println("【设备年限】设备年限预警定时发邮件(未处理),发送成功");
//                                            } else {
//                                                System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
//                                                System.out.println("【设备年限】设备年限预警定时发邮件(未处理),发送失败:" + result.getMsgCn());
//                                            }
//                                            // 更新 上次发送时间
//                                            pcbaDeviceDao.updateDeviceAgeCloseLastSendTime(time, pcbaDevice.getPcbaDeviceId());
//                                        }
//                                    }
//                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
            System.out.println("【设备年限】设备年限预警定时发邮件,发送失败");
        }
    }
}
